package Controller;

import DAO.UserDao;
import entity.Return;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet(name = "registerAction", value = "/registerAction")
public class registerController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        super.doGet(request, response);
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        super.doPost(request, response);
        String username = request.getParameter("username");
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String studentID = request.getParameter("studentID");
        String email = request.getParameter("email");
        String tel = request.getParameter("tel");
        String academy = request.getParameter("academy");

        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        System.out.println("Register:"+username+"........"+password);

        UserDao userDao = new UserDao();
        User user = userDao.queryRegister(username,name,password,studentID,email,tel,academy);
        if (user != null) {
            Return r = Return.ok().data("data",user);
            response.getWriter().println(r.toString());
            request.getSession().setAttribute("Result",r);
            request.getRequestDispatcher("jsp/login.jsp").forward(request, response);
        } else {
            Return r = Return.error().message("用户名已存在，请重新输入");
            response.getWriter().println(r.toString());
            request.getSession().setAttribute("Result",r);
            request.getRequestDispatcher("jsp/login.jsp").forward(request, response);
        }
    }
}
